package com.ocom.xfrecode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.entity.card.EntityXfGoodListDishes;
import com.ocom.common.entity.payconfig.EntityDishesInfo;
import com.ocom.common.request.payconfig.mealorder.GetOrderDishesRequest;
import com.ocom.common.request.web.GetPointMealSendReportsRequest;
import com.ocom.common.request.web.GetPointMealSendReportsXMRequest;
import com.ocom.common.request.xfrecde.GetUserOrdered;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.vo.xfrecode.GetPointMealSendVo;
import com.ocom.common.vo.xfrecode.OrderedMealVo;
import com.ocom.xfrecode.mapper.XfGoodListDishesMapper;
import com.ocom.xfrecode.service.XfGoodListDishesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class XfGoodListDishesServiceImpl extends ServiceImpl<XfGoodListDishesMapper, EntityXfGoodListDishes> implements XfGoodListDishesService {

    @Autowired
    private XfGoodListDishesMapper xfGoodListDishesMapper;

    @Override
    public Page<EntityXfGoodListDishes> getOrderDishes(GetOrderDishesRequest request) {
        /**
         * select device_no,point_Id,merch_Id,p_Id,dept_Id,order_no,cons_time,meal_date,meal_no
         * ,case when sum(if_refund)=count(if_refund) then '已退款' when  sum(if_refund)=0 then '未退款' else '部分退款' end if_refund
         * ,GROUP_CONCAT( Id,':', dishes_name,':',weight_number,':',dishes_price,':',if_refund  SEPARATOR ';') dishesDetail
         * ,sum(dishes_price) amount
         * from xf_goods_list_yyyyMM
         * where com_Id=#{comId} and merch_Id=#{merchId} and point_Id=#{pointId} and order_no=#{orderNo}
         * and meal_date between #{beginDate} and #{endDate}
         * and p_Id in (#{pIds}) and if_refund =#{ifRefund}
         *
         * and receipt_Id in (#{receiptIds})
         * group by order_no
         * order by meal_date desc ,meal_no desc,cons_time desc
         */
        QueryWrapper<EntityXfGoodListDishes> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", request.getComId());
        if (request.getMerchId() != null) {
            queryWrapper.eq("merch_id", request.getMerchId());
        }
        if (request.getPointId() != null) {
            queryWrapper.eq("point_id", request.getPointId());
        }
        if (!CommonUtil.isNull(request.getOrderNo())) {
            queryWrapper.eq("order_no", request.getOrderNo());
        }
        if (request.getIfRefund() != -1) {
            queryWrapper.eq("if_refund", request.getIfRefund());
        }
        if (request.getIds() != null && request.getIds().size() > 0) {
            queryWrapper.in("p_id", request.getIds());
        }
        if (request.getReceiptIds() != null && request.getReceiptIds().size() > 0) {
            queryWrapper.in("receipt_id", request.getReceiptIds());
        }
        queryWrapper.between("meal_date", request.getBeginDate(), request.getEndDate());
        List<String> dates = new ArrayList<>();
        try {
            String start = request.getBeginDate().substring(0, 7).replace("-", "");
            String end = request.getEndDate().substring(0, 7).replace("-", "");
            dates = DateUtils.getMonthBetween(start, end);

        } catch (Exception e) {
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】", "获取消费记录信息", request, e);
        }
        if (dates.size() > 1) {
            throw new RuntimeException("不支持跨月查询");
        }
        List<String> finalDates = dates;
        //日期范围查询
        queryWrapper.and(wrapper -> {
            for (String info : finalDates) {
                wrapper.or().eq("month_value", info);
            }
        });

        queryWrapper.select("order_no", "device_no", "point_id", "merch_id", "p_id", "dept_id", "cons_time", "meal_date", "meal_no", "month_value", "com_id",
                "(case when sum(if_refund)=count(if_refund) then '已退款' when  sum(if_refund)=0 then '未退款' else '部分退款' end)  as refundStatus",
                "GROUP_CONCAT( id,\";\", dishes_name,\";\",weight_number,\";\",dishes_price,\";\",if_refund,\"#\") as  dishesDetail",
                "sum(dishes_price) as amount"
        );
        queryWrapper.groupBy("order_no");
        queryWrapper.orderByDesc("meal_date", "meal_no", "cons_time");

        Page<EntityXfGoodListDishes> page = new Page<>(request.getPage(), request.getSize());
        return xfGoodListDishesMapper.selectPage(page, queryWrapper);
//		return this.list(queryWrapper);
    }

    @Override
    public Page<EntityXfGoodListDishes> getOrderDishesB(GetOrderDishesRequest request) {

        QueryWrapper<EntityXfGoodListDishes> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", request.getComId());
        if (request.getMerchId() != null) {
            queryWrapper.eq("merch_id", request.getMerchId());
        }
        if (request.getPointId() != null) {
            queryWrapper.eq("point_id", request.getPointId());
        }
        if (!CommonUtil.isNull(request.getOrderNo())) {
            queryWrapper.eq("order_no", request.getOrderNo());
        }
        if (request.getIfRefund() != -1) {
            queryWrapper.eq("if_refund", request.getIfRefund());
        }
        if (request.getIds() != null && request.getIds().size() > 0) {
            queryWrapper.in("p_id", request.getIds());
        }
        if (request.getReceiptIds() != null && request.getReceiptIds().size() > 0) {
            queryWrapper.in("receipt_id", request.getReceiptIds());
        }
        queryWrapper.between("meal_date", request.getBeginDate(), request.getEndDate());
        List<String> dates = new ArrayList<>();
        try {
            String start = request.getBeginDate().substring(0, 7).replace("-", "");
            String end = request.getEndDate().substring(0, 7).replace("-", "");
            dates = DateUtils.getMonthBetween(start, end);

        } catch (Exception e) {
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】", "获取消费记录信息", request, e);
        }
        List<String> finalDates = dates;
        //日期范围查询
        queryWrapper.and(wrapper -> {
            for (String info : finalDates) {
                wrapper.or().eq("month_value", info);
            }
        });

//		queryWrapper.select(  "order_no","device_no","point_id","merch_id","p_id","dept_id","cons_time","meal_date","meal_no","month_value","com_id","dishes_price",
////				"(case when sum(if_refund)=count(if_refund) then '已退款' when  sum(if_refund)=0 then '未退款' else '部分退款' end)  as refundStatus",
////				"GROUP_CONCAT( id,\";\", dishes_name,\";\",weight_number,\";\",dishes_price,\";\",if_refund,\"#\") as  dishesDetail",
//				"sum(dishes_price) as amount"
//		);
        Page<EntityXfGoodListDishes> page = new Page<>(request.getPage(), request.getSize());
//		queryWrapper.groupBy("order_no");
        queryWrapper.orderByDesc("meal_date", "meal_no", "cons_time");

//		PageHelper.startPage(request.getPage(), request.getSize());
//		List<EntityXfGoodListDishes> list = this.list(queryWrapper);
//		return new PageInfo<EntityXfGoodListDishes>(list);

        return xfGoodListDishesMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<OrderedMealVo> getUserOrdered(GetUserOrdered request) {
        QueryWrapper<EntityXfGoodListDishes> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", request.getComId());
        queryWrapper.eq("p_id", request.getPId());
        queryWrapper.eq("if_refund", 0);

        queryWrapper.between("meal_date", request.getBeginDate(), request.getEndDate());

        String lastMonth = request.getBeginDate().substring(0,7).replace("-","");
        if(request.getBeginDate().substring(0,7).equals(request.getEndDate().substring(0,7))){
            //同月往前查一个月
            lastMonth = DateUtils.getLastMonth(lastMonth, 1);
        }


        List<String> dates = new ArrayList<>();
        try {
            String start = lastMonth;
            String end = request.getEndDate().substring(0, 7).replace("-", "");
            dates = DateUtils.getMonthBetween(start, end);

        } catch (Exception e) {
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】", "获取消费记录信息", request, e);
        }
        List<String> finalDates = dates;
        queryWrapper.select("meal_date", "meal_no");
        queryWrapper.groupBy("meal_date", "meal_no");

        List<EntityXfGoodListDishes> list = new ArrayList<>();
        if(dates.size()>1){
            for (String month:dates){
                QueryWrapper<EntityXfGoodListDishes> queryWrapper1 = queryWrapper.clone();
                queryWrapper1.eq("month_value", month);
                List<EntityXfGoodListDishes> list2 =  this.list(queryWrapper1);
                if(list2 != null && list2.size()>0) list.addAll(list2);
            }
        }else{
            queryWrapper.and(wrapper -> {
                for (String info : finalDates) {
                    wrapper.or().eq("month_value", info);
                }
            });
            list = this.list(queryWrapper);
        }

        //日期范围查询
//        queryWrapper.and(wrapper -> {
//            for (String info : finalDates) {
//                wrapper.or().eq("month_value", info);
//            }
//        });
//        queryWrapper.select("meal_date", "meal_no");
//        queryWrapper.groupBy("meal_date", "meal_no");
//        List<EntityXfGoodListDishes> list = this.list(queryWrapper);

        List<OrderedMealVo> list2 = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (EntityXfGoodListDishes dishes : list) {
                OrderedMealVo orderedMealVo = new OrderedMealVo();
                orderedMealVo.setMealNo(dishes.getMealNo());
                orderedMealVo.setMealDate(DateUtils.parseDateToStr("yyyy-MM-dd", dishes.getMealDate()));
                list2.add(orderedMealVo);
            }
        }

        return list2;
    }

    @Override
    public Map<String, Object> getMealSendReportsXMByGoods(GetPointMealSendReportsXMRequest request) {
        QueryWrapper<EntityXfGoodListDishes> queryWrapper = new QueryWrapper<>();


        StringBuilder select = new StringBuilder();

        select.append("receipt_id,dishes_id,dishes_name,sum(weight_number) as weight_number ");

//        Map<String, String> dishesMap = new HashMap<>();

//        for (int i = 0; i < request.getDishesList().size(); i++) {
//            GetOrderPlanDishesResponse getOrderPlanDishesResponse = request.getDishesList().get(i);
//            String key = "dishesId" + i;
//            dishesMap.put(key, getOrderPlanDishesResponse.getDishesName());
//
//            select.append(" sum(case when dishes_id = ");
//            select.append(getOrderPlanDishesResponse.getDishesId());
//            select.append(" then weight_number else 0 end) as ");
//            select.append(key);
//            select.append(" , ");
//        }
//        select.append("sum(weight_number) as dishesAll ");

        queryWrapper.select(select.toString());

        queryWrapper.eq("com_id", request.getComId());
        queryWrapper.eq("meal_date", request.getMealDate());
        queryWrapper.eq("meal_no", request.getMealNo());
        queryWrapper.eq("if_refund", 0);

        if (null != request.getPointId()) {
            queryWrapper.eq("point_id", request.getPointId());
        }

        if (null != request.getReceiptId()) {
            queryWrapper.eq("receipt_id", request.getReceiptId());
        }

        if (StringUtils.isNotBlank(request.getReceiptName())) {
            queryWrapper.like("receipt_name", request.getReceiptName());
        }

        List<String> dates = new ArrayList<>();
        try {
            Date date = DateUtils.getDate(request.getMealDate(), DateUtils.YYYY_MM_DD);

            String strDate = DateUtils.getStrDate(date, DateUtils.YYYYMM);

            dates.add(strDate);

            String lastMonth = DateUtils.getLastMonth(strDate, 1);
            dates.add(lastMonth);
        } catch (Exception e) {
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】", "获取getMealSendReportsXM月份信息", request, e);
        }
        List<String> finalDates = dates;
        //日期范围查询
        queryWrapper.and(wrapper -> {
            for (String info : finalDates) {
                wrapper.or().eq("month_value", info);
            }
        });

        queryWrapper.groupBy("receipt_id","dishes_id");
        queryWrapper.orderByDesc("receipt_id");

        List<EntityXfGoodListDishes> list = this.list(queryWrapper);

        List<EntityDishesInfo> dishesInfos = new ArrayList<>();

        if (list != null && list.size() > 0) {

            for (EntityXfGoodListDishes entityXfGoodListDishes:list){
                List<Integer> classIds = dishesInfos.stream().map(EntityDishesInfo::getDishesId).collect(Collectors.toList());
                if(!classIds.contains(entityXfGoodListDishes.getDishesId())){
                    EntityDishesInfo entityDishesInfo =new EntityDishesInfo();
                    entityDishesInfo.setDishesId(entityXfGoodListDishes.getDishesId());
                    entityDishesInfo.setDishesName(entityXfGoodListDishes.getDishesName());
                    dishesInfos.add(entityDishesInfo);
                }
            }

        }



        Map<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("dishes", dishesInfos);
        return map;
    }


    @Override
    public Page<EntityXfGoodListDishes> getOrderDishesC(GetOrderDishesRequest request) {

//        QueryWrapper<EntityXfGoodListDishes> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("com_id", request.getComId());
//        if (request.getMerchId() != null) {
//            queryWrapper.eq("merch_id", request.getMerchId());
//        }
//        if (request.getPointId() != null) {
//            queryWrapper.eq("point_id", request.getPointId());
//        }
//        if (!CommonUtil.isNull(request.getOrderNo())) {
//            queryWrapper.eq("order_no", request.getOrderNo());
//        }
//        if (request.getIfRefund() != -1) {
//            queryWrapper.eq("if_refund", request.getIfRefund());
//        }
//        if (request.getIds() != null && request.getIds().size() > 0) {
//            queryWrapper.in("p_id", request.getIds());
//        }
//        if (request.getReceiptIds() != null && request.getReceiptIds().size() > 0) {
//            queryWrapper.in("receipt_id", request.getReceiptIds());
//        }
//        queryWrapper.between("meal_date", request.getBeginDate(), request.getEndDate());
//        List<String> dates = new ArrayList<>();
//        try {
//            String start = request.getBeginDate().substring(0, 7).replace("-", "");
//            String end = request.getEndDate().substring(0, 7).replace("-", "");
//            dates = DateUtils.getMonthBetween(start, end);
//
//        } catch (Exception e) {
//            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】", "获取消费记录信息", request, e);
//        }
//        List<String> finalDates = dates;
//        //日期范围查询
//        queryWrapper.and(wrapper -> {
//            for (String info : finalDates) {
//                wrapper.or().eq("month_value", info);
//            }
//        });
//
//
//        Page<EntityXfGoodListDishes> page = new Page<>(request.getPage(), request.getSize());
//
//        queryWrapper.orderByDesc("meal_date", "meal_no", "cons_time");

        Page<EntityXfGoodListDishes> goodListDishesPage =new Page<>();

        request.setPage((request.getPage()-1)*request.getSize());
        request.setSize(request.getSize());

        goodListDishesPage.setTotal(xfGoodListDishesMapper.getOrderDishesCCount(request));
        goodListDishesPage.setRecords(xfGoodListDishesMapper.getOrderDishesC(request));
        request.setPage(request.getPage());
        request.setSize(request.getSize());

        return goodListDishesPage;
    }



    @Override
    public List<GetPointMealSendVo> getPointMealSend(GetPointMealSendReportsRequest request) {

        List<GetPointMealSendVo> pointMealPreList = new ArrayList<>();

        /**
         * select point_id,meal_date,meal_no,receipt_id ,receipt_name
         * 	,sum(case when cons_state in (3,5) then 1  else 0 end ) as  dcTimes
         * 	,sum(case when cons_state=4 then 1  else 0 end ) as  qcTimes
         * 	,sum(case when cons_state=6 then 1  else 0 end ) as  tcTimes
         * 				from xf_record_202406
         * 				where com_id =#{comId}   and cons_state in (3,4,5,6)
         *  if(#{pointId} 不为空)  and point_id = #{pointId}
         *  			and meal_date between #{startTime}  and  #{endTime}
         * if(#{receiptId} 不为空)  and receipt_id = #{receiptId}
         * 	  if(#{receiptName} 不为空)  and receipt_name  like  '%#{receiptName}%'
         * group by  point_id,meal_date,meal_no,receipt_id ,receipt_name
         * order  by  point_id,meal_date,meal_no,receipt_id ,receipt_name
         */


        QueryWrapper<GetPointMealSendReportsRequest> queryWrapper = Wrappers.query();

        String lastMonth = request.getStartTime().substring(0,7).replace("-","");
        if(request.getStartTime().substring(0,7).equals(request.getEndTime().substring(0,7))){
            //同月往前查一个月
            lastMonth = DateUtils.getLastMonth(lastMonth, 1);
        }
        List<String> dates = new ArrayList<>();
        try {
            String start3 = lastMonth;
            String end3 = request.getEndTime().substring(0, 7).replace("-", "");
            dates = DateUtils.getMonthBetween(start3, end3);
        } catch (Exception e) {
            log.info("请求方式:【{}】,查询的请求的数据:【{}】,异常信息:【{}】", "获取消费记录信息", request, e);
        }


//        queryWrapper.select("o.point_id", "o.meal_date", "o.meal_no","o.receipt_id","o.receipt_name",
//                        "sum(case when cons_state in (3,5) then 1  else 0 end ) as  amount1",//dcTimes
//                        "sum(case when cons_state=4 then 1  else 0 end ) as  amount3", //qcTimes
//                        "sum(case when cons_state=6 then 1  else 0 end ) as  amount2")  //tcTimes
        queryWrapper.eq("g.com_id", request.getComId())
                .in("o.cons_state", 3, 4, 5, 6);

        if (request.getPointId() != null) {
            queryWrapper.eq("g.point_id", request.getPointId());
        }
        if (request.getReceiptId() != null) {
            queryWrapper.eq("g.receipt_id", request.getReceiptId());
        }

        if (!CommonUtil.isNull(request.getReceiptName())) {
            queryWrapper.like("g.receipt_name", request.getReceiptName());
        }

        queryWrapper.between("g.meal_date", request.getStartTime(), request.getEndTime());

        if(request.getType()==1){
            queryWrapper.groupBy("g.point_id", "g.meal_date", "g.meal_no","g.receipt_id","g.receipt_name")
                    .orderByAsc("g.point_id", "g.meal_date", "g.meal_no","g.receipt_id","g.receipt_name");
        }else{
            queryWrapper.groupBy("g.point_id", "g.meal_date", "g.meal_no","g.receipt_id","g.receipt_name","g.dishes_id")
                    .orderByAsc("g.point_id", "g.meal_date", "g.meal_no","g.receipt_id","g.receipt_name","g.dishes_id");
        }

        List<GetPointMealSendVo> entityXfRecords = new ArrayList<>();
        for (String month : dates) {
            QueryWrapper<GetPointMealSendReportsRequest> queryWrapper2 = queryWrapper.clone();
            queryWrapper2.eq("g.month_value", month);
            queryWrapper2.eq("o.month_value", month);
            List<GetPointMealSendVo> entityXfRecords3 = xfGoodListDishesMapper.getPointMealSend(queryWrapper2);
            if (entityXfRecords3 != null && entityXfRecords3.size() > 0) entityXfRecords.addAll(entityXfRecords3);
        }


        Map<String,GetPointMealSendVo> stringGetPointMealPreVoMap =new HashMap<>();

        if (entityXfRecords != null && entityXfRecords.size() > 0) {
            for (GetPointMealSendVo entityXfRecord : entityXfRecords) {
                String key = "point_id:"+entityXfRecord.getPointId()+"#meal_date:"+entityXfRecord.getMealDate()+ "#meal_no:"+
                        entityXfRecord.getMealNo() +"receipt_id:"+entityXfRecord.getReceiptId()+"receipt_name:"+entityXfRecord.getReceiptName();
                if(stringGetPointMealPreVoMap.containsKey(key)){
                    GetPointMealSendVo getPointMealPreVo =  stringGetPointMealPreVoMap.get(key);
                    getPointMealPreVo.setDcTimes(entityXfRecord.getDcTimes());
                    getPointMealPreVo.setTcTimes(entityXfRecord.getTcTimes());
                    getPointMealPreVo.setQcTimes(entityXfRecord.getQcTimes());
                    stringGetPointMealPreVoMap.put(key,getPointMealPreVo);
                }else{
                    GetPointMealSendVo getPointMealPreVo = new GetPointMealSendVo();
                    getPointMealPreVo.setMealDate(entityXfRecord.getMealDate());
                    getPointMealPreVo.setMealNo(entityXfRecord.getMealNo());
                    getPointMealPreVo.setPointId(entityXfRecord.getPointId().intValue());
                    getPointMealPreVo.setReceiptId(entityXfRecord.getReceiptId().intValue());
                    getPointMealPreVo.setReceiptName(entityXfRecord.getReceiptName());
                    getPointMealPreVo.setPointId(entityXfRecord.getPointId().intValue());
                    getPointMealPreVo.setDcTimes(entityXfRecord.getDcTimes());
                    getPointMealPreVo.setTcTimes(entityXfRecord.getTcTimes());
                    getPointMealPreVo.setQcTimes(entityXfRecord.getQcTimes());
                    getPointMealPreVo.setDishesId(entityXfRecord.getDishesId());
                    getPointMealPreVo.setDishesName(entityXfRecord.getDishesName());
                    stringGetPointMealPreVoMap.put(key,getPointMealPreVo);
                }
            }
            pointMealPreList = new ArrayList(stringGetPointMealPreVoMap.values());
        }

        return pointMealPreList;
    }

}
